import { onMounted, ref, shallowRef, watch } from "vue"
import { getBanner_api, getPersonalized_api, getTopPlaylist_api, getTopList_api, getPlaylistTrackAll_api } from '@/api/homePage'
import Utils from '@/utils/commonUtils'
export default function useHomePageApi() {
    // 轮播图
    const carouselList = shallowRef<any>([])
    const getBannerList = () => {
        getBanner_api().then((response: any) => {
            carouselList.value = response.banners
        }).catch(() => {
            Utils.openNotification('error', "请求失败，稍后再试")
        })
    }
    // 推荐歌单
    const personalizedList = shallowRef<any>([])
    const getPersonalizedList = () => {
        getPersonalized_api().then((response: any) => {
            personalizedList.value = response.result
        }).catch(() => {
            Utils.openNotification('error', "请求失败，稍后再试")
        })
    }
    // 精选歌单
    const topPlaylist = shallowRef<any>([])
    const getTopPlaylist = () => {
        getTopPlaylist_api().then((response: any) => {
            topPlaylist.value = response.playlists
        }).catch(() => {
            Utils.openNotification('error', "请求失败，稍后再试")
        })
    }
    // 排行榜
    const topList = ref<any>([])
    const getTopList = () => {
        getTopList_api().then((response: any) => {
            topList.value = response.list.slice(0, 4).map((item: any) => {
                const { name, id, updateFrequency, coverImgUrl: picUrl } = item
                const obj: any = { name, id, updateFrequency, picUrl, flag: false }
                return obj
            })
        }).catch(() => {
            Utils.openNotification('error', "请求失败，稍后再试")
        })
    }
    // 榜单精选列表
    const newTopList = shallowRef<any>([])
    const loading = ref<boolean>(false)
    watch(
        topList,
        () => {
            if (topList.value.length) {
                loading.value = false
                newTopList.value = topList.value.map((list: any) => {
                    getPlaylistTrackAll_api({ id: list.id, limit: 3 }).then((res: any) => {
                        list['songs'] = res.songs.map((item: any) => ({
                            name: item.name,
                            picUrl: item.al.picUrl,
                            author: item.ar.map((ar: any) => ar.name).join('/'),
                            id: item.id
                        }))
                    })
                    return list
                })
                loading.value = true
            }
        },
        { immediate: true }
    )
    onMounted(() => {
        getBannerList()
        getPersonalizedList()
        getTopPlaylist()
    })
    return {
        getTopList,
        carouselList,
        personalizedList,
        topPlaylist,
        newTopList,
        loading
    }
}
